package com.iraeta.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.iraeta.common.*;
import com.iraeta.entity.User;
import com.iraeta.service.UserService;
import com.iraeta.uitl.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController(value = "UserController")
@RequestMapping("user")
public class UserController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @RequestMapping("login")
    @AuthAccess
    public String userLogin(@RequestBody JSONObject paramJb){
        String userName = paramJb.getString("username");
        String pwd = paramJb.getString("password");
        User user = userService.getUserByUserName(userName, pwd);
        if(user == null){
            return JSONObject.toJSONString(Result.error("用户名密码不正确"));
        }
        //生产token等数据
        Map<String,String> data = new HashMap<>();
        String token = JwtUtil.getToken(user.getId().toString());
        data.put("token", token);
        return  JSONObject.toJSONString(Result.success(data));
    }

    @RequestMapping("info")
    public String userInfo(@RequestBody JSONObject paramJb){
        String token = paramJb.getString("token");
        if(StrUtil.isEmpty(token)) {
            return JSONObject.toJSONString(Result.error("非法访问"));
        }
        int userId = this.getUserId();
        if(userId == 0){
            return JSONObject.toJSONString(Result.error("非法访问"));
        }
        Map<String,String> data = new HashMap<>();
        data.put("name", this.getUserName());
        data.put("avatar", this.getUserAvatar());
        return JSONObject.toJSONString(Result.success(data));
    }

    @RequestMapping("logout")
    @AuthAccess
    public String userLogout(HttpServletRequest request){
        String token = request.getHeader("X-Token");
        MySessionManager.remove(token);
        return JSONObject.toJSONString(Result.success());
    }
}
